package nettyRPC.registry;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @program: NettyRpc-master
 * @description
 * @author: tkk fendoukaoziji
 * @create: 2019-08-07 18:23
 **/
public class ServiceRegistry {
    private static final Logger logger=LoggerFactory.getLogger(ServiceRegistry.class);
    private CountDownLatch latch=new CountDownLatch(1);
    private String registryAddress;
    public ServiceRegistry(String registryAddress){
        this.registryAddress=registryAddress;
    }


    public void register(String data){
        if(data!=null){
            ZooKeeper zooKeeper = connectServer();
            if(zooKeeper!=null){
                // Add root node if not exist
                AddRootNode(zooKeeper);
                createNode(zooKeeper,data);
            }
        }
    }

    //创建客户端
    private ZooKeeper connectServer(){
        ZooKeeper zk=null;
        try {
            zk=new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    if(watchedEvent.getState()==Event.KeeperState.SyncConnected){
                        latch.countDown();
                    }
                }
            });
            latch.wait();//同步阻塞  创建好了释放锁
        } catch (IOException e) {
           logger.error("",e);
        } catch (InterruptedException e) {
           logger.error("",e);
        }
        return zk;
    }

    /**
     * 添加根节点
     */
    private void AddRootNode(ZooKeeper zk) {
        Stat s= null;
        try {
            s = zk.exists(Constant.ZK_REGISTRY_PATH,false);
            if(s==null){
                zk.create(Constant.ZK_REGISTRY_PATH,new byte[0],ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (KeeperException e) {
           logger.error(e.toString());
        } catch (InterruptedException e) {
           logger.error(e.toString());
        }

    }


    private void createNode(ZooKeeper zk,String data){
        byte[] bytes = data.getBytes();
        try {
            String path = zk.create(Constant.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            logger.debug("create zookeeper node ({}=>{})",path,data);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}



















